import { Provide, Inject, Config } from '@midwayjs/core';
import { UserDao } from '../dao/userDao';
import { Context } from '@midwayjs/koa';
import { UserDTO, UserIdentityDTO } from '../dto/user';
import { BigIntService } from './bigInt.service';
import { GetFileExtension } from './originelFileName.service';
import { OSSService } from '@midwayjs/oss';
import { uuidv7 } from 'uuidv7';
import { join } from 'path';
import { PageDTO } from '../dto/page';
import * as bcrypt from 'bcryptjs';
import { UploadFileInfo } from '@midwayjs/busboy';
import { JwtService } from '@midwayjs/jwt';

@Provide()
export class UserService {
  @Inject()
  userDao: UserDao;
  @Inject()
  ctx: Context;
  @Inject()
  jwtService: JwtService;
  @Inject()
  bigIntService: BigIntService;
  @Inject()
  getFileExtension: GetFileExtension;
  @Inject()
  ossService: OSSService;
  @Config('jwtConfig') // 动态注入配置
  jwtConfig: { secret: string; expiresIn: string | number };

  // 通过用户 ID 查找用户
  async findUserById(userId: UserDTO['userId']) {
    // 从数据库中查询用户信息
    const user = await this.userDao.findUserById(userId);
    return user;
  }

  // 通过账号邮箱密码查找用户
  async findAccount(field: string, value: string) {
    // 从数据库中查询用户信息
    const user = await this.userDao.findAccount(field, value);
    return user;
  }

  // 删除用户
  async deleteUser(userId: UserDTO['userId']) {
    // 从数据库中删除用户信息
    const result = await this.userDao.delUser(userId);
    return result;
  }

  //上传图片
  async uploadImg(files: Array<UploadFileInfo>) {
    // 获取文件扩展名
    const originalFilename = this.getFileExtension.getFileExtension(
      files[0].filename
    );
    // 使用 UUID 创建唯一文件名
    const filename = uuidv7() + '.' + originalFilename;
    // 构建上传文件的目标路径（根据需求可以更改路径）
    const targetPath = join('oss', filename);
    // 上传文件到 OSS
    const result = await this.ossService.put(targetPath, files[0].data); // 这里传递文件的路径
    if (result) {
      // 上传成功，保存文件的 URL 地址到数据库
      const fileUrl = result.url;
      return await this.userDao.uploadImg(fileUrl);
    } else {
      throw new Error('上传图片失败');
    }
  }
  //修改用户信息
  async updateUserInfo(userId: UserDTO['userId'], updateUserDto: any) {
    if (updateUserDto.password) {
      updateUserDto.password = await bcrypt.hash(updateUserDto.password, 10);
    }
    return await this.userDao.updateUserInfo(userId, updateUserDto);
  }
  //获取用户信息
  async getUserInfo() {
    const user = await this.userDao.findUserById(this.ctx.state.user.userId);
    return await this.jwtService.sign(
      {
        userId: user.userId,
        departmentId: user.departmentId,
        departmentName: user.departmentName,
        account: user.account,
        name: user.name,
        identity: user.identity,
        sex: user.sex,
        phone: user.phone,
        email: user.email,
        authenticationFlag: user.authenticationFlag,
        directorFlag: user.directorFlag,
        userRole: user.role,
      },
      this.jwtConfig.secret,
      {
        expiresIn: this.jwtConfig.expiresIn,
      }
    );
  }
  //管理员获取用户验证身份图片
  async getUserIdentityImg(pageDto: PageDTO) {
    return this.bigIntService.bigInt(
      await this.userDao.getUserIdentityImg(pageDto)
    );
  }
  //管理员审批用户验证图片
  async approveUserIdentityImg(userIdentityDto: UserIdentityDTO) {
    return await this.userDao.approveUserIdentityImg(userIdentityDto);
  }
  //管理员获取所有用户信息
  async getAllUser(allUserDto: PageDTO) {
    return this.bigIntService.bigInt(await this.userDao.getAllUser(allUserDto));
  }
}
